﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;

using WCFThree.Abstract;
namespace WCFThree.Proxy
{
    public class RemoteServiceFactory
    {
        private string GetUrl(string Operate)
        {
            return string.Format("http://localhost:8733/Design_Time_Addresses/WCFThree.Service/{0}/", Operate);
        }
        /// <summary>
        /// 获取学生操作
        /// </summary>
        /// <returns></returns>
        public IStudent GetStudent()
        {
            string url = GetUrl("Student");
            return CreateService<IStudent>(url);
        }
        public IScore GetScore()
        {
            return CreateService<IScore>(GetUrl("Score"));
        }
        public IUserInfo GetUserInfo()
        {
            return CreateService<IUserInfo>(GetUrl("UserInfo"));
        }
        private T CreateService<T>(string url)
        {
            var binding = new BasicHttpBinding();
            binding.MaxReceivedMessageSize = maxReceivedMessageSize;
            binding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas();
            binding.ReaderQuotas.MaxStringContentLength = maxReceivedMessageSize;
            binding.ReaderQuotas.MaxArrayLength = maxReceivedMessageSize;
            binding.ReaderQuotas.MaxBytesPerRead = maxReceivedMessageSize;

            ChannelFactory<T> chan = new ChannelFactory<T>(binding, new EndpointAddress(url));
            //异常处理注册
            //cha.Endpoint.EndpointBehaviors.Add();
            foreach (var op in chan.Endpoint.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
                // 获取或设置对象图中要序列化或反序列化的最大项数。
                if (dataContractBehavior != null)
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
            }
            chan.Open();
            return chan.CreateChannel();
        }
        private const int maxReceivedMessageSize = 2147483647;
    }
}
